﻿using log4net;
using MySql.Data.MySqlClient;
using server;
using server.Business;
using server.DAO;
using server.Model;
using server.Tool;
using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Activation;

namespace Restful
{
    //多线程
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Multiple, IncludeExceptionDetailInFaults = true)]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]

    
    ////此脚本存在sql 漏洞注入的风险，后续有时间优化。

    public class ServiceImp : IService
    {
        ILog Logger = log4net.LogManager.GetLogger("Restful.ServiceImp");

        private JoinRoomDao joinRoomDao = new JoinRoomDao();
        private UserRoomDao userRoomDao = new UserRoomDao();
        private SearchGrounpDao searchGrounpDao = new SearchGrounpDao();
        private GrounpLifeDao grounpLifeDao = new GrounpLifeDao();
        private LifeDao lifeDao = new LifeDao();
        private GrounpDao grounpDao = new GrounpDao();
        private EditGrounpDao editGrounpDao =new EditGrounpDao();
        private ChatHandle chatBusiness = new ChatHandle();
        private UserDao userDao = new UserDao();
        private CURDRoomDao curdRoomDao = new CURDRoomDao();
        private KnapsackDao knapsackDao = new KnapsackDao();
        private GameTemplateDao gameTemplateDao = new GameTemplateDao();

        public int Save(string json)
        {

            string[] strs = json.Split('|');
            string grounpId = strs[0];
            string fenceLon = strs[1];
            string fenceLat = strs[2];
            string fenceRadius = strs[3];
            string updateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            string sql = "update  grounp set fenceLon = '" + fenceLon + "', fenceLat = '" + fenceLat +
                "', fenceRadius = '" + fenceRadius + "', fenceTotalRadius = '" + fenceRadius + "', createTime = '" + updateTime + "' where id = @grounpId;";
           // Logger.InfoFormat("update fence save sql ={0}", sql);
            int count = MySqlExecuteTools.GetCountResult(sql, new MySqlParameter[] { new MySqlParameter("@grounpId", grounpId) });
            return 0;
        }

        public string SearchGameStateByGrounp(string grounpId)
        {
            // throw new NotImplementedException();
            string sql = "select * from grounp where id = @grounpId  and runState = 0";
            int count = MySqlExecuteTools.GetCountResult(sql, new MySqlParameter[] { new MySqlParameter("@grounpId", grounpId) });
            if (count > 0)
            {
                return "0";
            }
            else
            {
                return "1";
            }
        }

        public string ClearRoomList(string grounpId)
        {

            return editGrounpDao.ClearAllRoomData(grounpId);
        }

        #region chat message
        private RoomDao roomDao = new RoomDao();
        public string GetMessage(string userId)
        {
            // throw new NotImplementedException();

            return "";
        }

        /// <summary>
        /// roomid|content
        /// </summary>
        /// <param name="json"></param>
        public string SendChatMessage(string json)
        {
            return  chatBusiness.SendChatMessage(json, roomDao);
        }


        #endregion

        public string ShowDebug(string info)
        {
            Console.WriteLine("调试信息:{0}",info);
            return info;
        }

        /// <summary>
        /// 设置玩家准备好了状态
        /// </summary>
        /// <param name="userId"></param>
        public string SetPlayerReadyOk(string userId)
        {
            return  userRoomDao.SetPlayerReadyOk(userId);
        }

        public string SetPlayerCancelReady(string userId)
        {
            return userRoomDao.SetPlayerCancelReady(userId);
        }

        /// <summary>
        /// 检查游戏运行状态
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public  int CheckGameRunState(string json)
        {
            string[] strs = json.Split('|');
            string userId = strs[0];
            string userType = strs[1];
            int  result= searchGrounpDao.CheckGameRunState(userId, userType);
           // Console.WriteLine(result);
            return result;
        }

     
        public string GetRoomList(string adminUserId)
        {
           List<Room> roomList =   joinRoomDao.GetRoomListByAdmin(int.Parse(adminUserId));
            return Utils.CollectionsConvert.ToJSON(roomList);
        }
        public int IsEditRoom(string roomId, string userId)
        {
            return  joinRoomDao.IsEditRoom(roomId, userId);
        }

        public string GetRoomUserTreeData(string userId)
        {
            return searchGrounpDao.GetRoomUserTreeData(userId);
        }

        public string GetRemainTime(string userId,string userType)
        {

            return grounpDao.GetRemainTime(userId, userType);
        }

        public string GetLeaderAuthority(string userId)
        {
            string sql = "select * from room where userId = @userId";
            List<Room> roomList = MySqlExecuteTools.GetObjectResult<Room>(sql, new MySqlParameter[] { new MySqlParameter("@userId", userId) });
            if (roomList != null && roomList.Count > 0)
            {
                return "1";
            }
            else
            {
                return "0";
            }
        }

        public string GetRoomByUser(string userId)
        {
            string sql = "select * from room_user where user_id = @user_id";
            List<Room_User> roomUserList = MySqlExecuteTools.GetObjectResult<Room_User>(sql,
              new MySqlParameter[] { new MySqlParameter("@user_id", userId) });

            if(roomUserList!=null && roomUserList.Count>0)
            {
                return roomUserList[0].room_id.ToString();
            }
            else
            {
                 return  "-1";
            }
        }

        #region start Stop game
        public string StopGame(string grounpId)
        {
           return editGrounpDao.StopGame(grounpId);
        }


        /// <summary>
        /// 启动游戏
        /// </summary>
        /// <param name="grounpId"></param>
        /// <returns></returns>
        public string StartGame(string grounpId)
        {
            return grounpDao.StartGame(grounpId);
        }

        public string ModifyUser(string userId, string userName, string oldPassword, string newPassword,string userType)
        {
            return userDao.ModifyUser( userId,  userName,  oldPassword,  newPassword, userType);
        }



        #endregion

        public string CheckPlayerIsJoinState(string userId, string userType)
        {
            //throw new NotImplementedException();
            return joinRoomDao.CheckPlayerIsJoinState(userId, userType);
        }

        public DataResult CREATE_EDIT_ROOM(string grounpId, string gamePassword, string roomId, string roomName, string roomPassword,string userId)
        {
            return curdRoomDao.CreateEditRoom(grounpId,  gamePassword,  roomId,  roomName,  roomPassword, userId);
        }

        public DataResult JoinRoom(string checkCode, string grounpId, string roomId, string userId, string userName)
        {
            return joinRoomDao.JoinRoom(checkCode, grounpId, roomId, userId, userName);
        }

        public string CheckGameReadyState(string grounpId)
        {
            return grounpDao.CheckGameReadyState(grounpId);
        }

        public string CheckGameIsSetFinish(string grounpId)
        {
            return grounpDao.CheckGameIsSetFinish(grounpId);
        }

        public string ForgetPassword(string telephone, string newPassword)
        {

            return userDao.ForgetPassword(telephone, newPassword);
        }

        public string CheckRoomState(string UserId)
        {
            string sql = "select * from room where userId = @userId";
            List<Room> roomList = MySqlExecuteTools.GetObjectResult<Room>(sql,
              new MySqlParameter[] { new MySqlParameter("@userId", UserId) });

            if (roomList != null && roomList.Count > 0)
            {
                return roomList[0].runState.ToString();
            }
            else
            {
                return "-1";
            }

        }

        public string SetLeaderReadyCancel(string userId)
        {
            return  userRoomDao.SetLeaderReadyCancel(userId);
        }

        public string GetRemainFireTime(string userId, string userType)
        {
            return grounpDao.GetFireRemainTime(userId, userType);
        }

        public string IsFireTime(string userId, string userType)
        {
            return grounpDao.IsFireTime(userId, userType);
        }

        public string ResetGameConfig(string grounpId)
        {
            return  gameTemplateDao.ResetGameConfig(grounpId, editGrounpDao, knapsackDao);
        }

        public string SaveGameTemplate(string grounpId, string Name)
        {
            return gameTemplateDao.SaveGameTemplate(grounpId, Name);
        }

        public string RestoreGameTemplate(string id)
        {
            return gameTemplateDao.RestoreGameTemplate(id,knapsackDao);
        }

        public string DelGameTemplate(string id)
        {
            return gameTemplateDao.DelGameTemplate(id);
        }

        public string CheckGameTemplate(string grounpId)
        {
            return gameTemplateDao.CheckGameTemplate(grounpId);
        }

        public string GetGameTemplateList(string grounpId)
        {
            return gameTemplateDao.GetGameTemplateList(grounpId);


        }

        public string CopyGameTemplate(string id)
        {
            return gameTemplateDao.CopyGameTemplate(id);
        }

        public string UpdateGameTemplateName(string id, string tname)
        {
            //throw new NotImplementedException();
            return gameTemplateDao.UpdateGameTemplateName(id, tname);
        }

        public void SaveTestData(TestDataItem data)
        {
            string _data = data.data;
            Logger.Debug(_data);
            string sql = "insert into testdata(data) " +
                  "values('" + _data + "')";
            long newID = MySqlExecuteTools.GetAddID(sql);
        }

        
    }
}
